package com.yf.utils;

import java.util.HashMap;
import java.util.Map;

public class UserContext {
    private static ThreadLocal<Map<String, Object>> threadLocal;

    private static final String KEY_USER_ID = "uid";
    private static final String KEY_BLACK_USER = "black";
    private static final String KEY_USER_ROLE = "role";

    static {
        threadLocal = new ThreadLocal<>();
    }

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(6);
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<>(6);
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static void setUserId(Integer uid) {
        set(KEY_USER_ID, uid);
    }

    public static Integer getUserId() {
        Object value = get(KEY_USER_ID);
        if (value == null) {
            return 0;
        }
        return Integer.valueOf(value.toString());
    }

    public static void markBlackUser(Boolean tag) {
        set(KEY_BLACK_USER, tag);
    }

    public static Boolean getBlackUserMark() {
        Object v = get(KEY_BLACK_USER);
        if (v == null) {
            return false;
        }
        return Boolean.valueOf(v.toString());
    }

    public static void setUserRole(Integer uid) {
        set(KEY_USER_ROLE, uid);
    }

    public static Integer getUserRole() {
        Object v = get(KEY_USER_ROLE);
        if (v == null) {
            return 0;
        }
        return (Integer) v;
    }
}
